<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      height="550"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" width="150" align="center">
        <template slot-scope="{row}">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="轮播图片" width="120" align="center">
        <template slot-scope="{row}">
          <el-image :src="getImage(row.pic)" fit="fit" />
        </template>
      </el-table-column>
      <el-table-column label="顶栏背景色" width="150" align="center">
        <template slot-scope="{row}">
          <span :style="'width: 120px; height: 30px;padding: 5px;color: #fff;background-color:' + row.bar_color + ';'">{{ row.bar_color }}</span>
        </template>
      </el-table-column>
      <el-table-column label="关联链接" width="120" align="center">
        <template slot-scope="{row}">
          <span>{{ row.url }}</span>
        </template>
      </el-table-column>
      <el-table-column label="跳转方式" width="120" align="center">
        <template slot-scope="{row}">
          <span>{{ getOpenTypeString(row.open_type) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="显示位置" width="100" align="center">
        <template slot-scope="{row}">
          <span>{{ getPositionString(row.position) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="100" align="center">
        <template slot-scope="{row}">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusString(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" prop="sort_id" sortable="custom" align="center" width="80" :class-name="getSortClass('sort_id')">
        <template slot-scope="{row}">
          <span>{{ row.sort_id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="描述" width="120" align="center">
        <template slot-scope="{row}">
          <span>{{ row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="200" class-name="small-padding fixed-width">
        <template slot-scope="{row, $index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button
            v-if="row.status==0"
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog class="data-form-dialog" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px" style="width: 450px;">
        <el-form-item
          label="标题"
          prop="title"
          :rules="[
            { required: true, message: '请填写标题'},
            { type: 'string', message: '标题必需是字符串'},
            { min: 0, max: 64, message: '长度最长64'}
          ]"
        >
          <el-input v-model="temp.title" />
          <div class="input-tip-cloum">区分轮播图</div>
        </el-form-item>

        <el-form-item label="显示位置">
          <el-select v-model="temp.position" class="filter-item" placeholder="请选择位置">
            <el-option v-for="(item, key) in positionOptions" :key="key" :label="item.label" :value="item.key" />
          </el-select>
        </el-form-item>

        <el-form-item
          label="轮播图片"
          prop="pic"
          :rules="[
            { required: true, message: '请上传轮播图'},
            { min: 0, max: 255, message: '长度最长255'}
          ]"
        >
          <ImgCutter :rate="imgRate" @cutDown="cutDown">
            <div slot="open" class="icon-uploader">
              <el-image v-if="temp.pic" :src="temp.pic" class="cate-icon" width="2.5rem">
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline" />
                </div>
              </el-image>
              <i v-else class="el-icon-plus cate-uploader-icon" />
            </div>
          </ImgCutter>
        </el-form-item>

        <el-form-item
          label="顶栏背景色"
          prop="bar_color"
          :rules="[
            { min: 0, max: 7, message: '16进颜色值'}
          ]"
        >
          <el-input v-model="temp.bar_color" />
          <div class="input-tip-cloum">顶栏背景色，16进颜色值， 如白色#FFFFFF</div>
        </el-form-item>

        <el-form-item
          label="描述"
          prop="description"
          :rules="[
            { type: 'string', message: '描述必需是字符串'},
            { min: 0, max: 128, message: '长度最长128'}
          ]"
        >
          <el-input v-model="temp.description" />
          <div class="input-tip-cloum">说明轮播图的用途</div>
        </el-form-item>

        <el-form-item
          label="关联链接"
          prop="url"
          :rules="[
            { min: 0, max: 255, message: '长度最长255'}
          ]"
        >
          <el-input v-model="temp.url" />
        </el-form-item>

        <el-form-item v-if="temp.url" label="链接打开方式">
          <el-select v-model="temp.open_type" class="filter-item" placeholder="请选择打开方式">
            <el-option v-for="(item, key) in this.$store.state.settings.openTypeOptions" :key="key" :label="item.label" :value="item.key" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="temp.status" class="filter-item" placeholder="请选择状态">
            <el-option v-for="(item, key) in statusOptions" :key="item" :label="item" :value="key" />
          </el-select>
        </el-form-item>

        <el-form-item
          label="排序"
          prop="sort_id"
          :rules="[
            { type: 'number', message: '排序必须为数字值'}
          ]"
        >
          <el-input-number v-model.number="temp.sort_id" :step="10" :min="0" />
          <span class="input-tip-text">数值越大排位越前</span>
        </el-form-item>

        <el-form-item
          label="可见会员等级"
          prop="show_level"
          :rules="[
            { type: 'number', message: '可见会员等级数必须为数字值'}
          ]"
        >
          <el-input-number v-model.number="temp.show_level" :step="1" :min="0" />
          <span class="input-tip-text">级，(0-100级)</span>
          <div class="input-tip-cloum">此等级（含）以上的会员才可见。</div>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" :loading="submitLoading" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchCarouselList, fetchCreateCarousel, fetchUpdateCarousel, fetchDeleteCarousel } from '@/api/carousel'
import { fetchImageUploadNoWater } from '@/api/upload'
import ImgCutter from 'vue-img-cutter'

export default {
  name: 'Carousel',
  components: { ImgCutter },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      submitLoading: false, // 提交中
      showReviewer: false,
      dialogFormVisible: false,
      dialogStatus: '',
      statusType: ['danger', 'success'],
      statusOptions: ['下架', '上架'],
      positionOptions: [
        { key: 0, label: '首页', rate: '414:150' },
        { key: 1, label: '会员中心', rate: '350:76' }
      ],
      listQuery: {
        sort_id: '-id'
      },
      temp: {
        id: 0,
        title: '',
        url: '',
        bar_color: '',
        open_type: '',
        description: '',
        status: 1,
        pic: '',
        show_level: 0,
        position: 0,
        sort_id: 0
      },
      textMap: {
        update: '编辑',
        create: '添加'
      },
      rules: {
      }
    }
  },
  computed: {
    imgRate: {
      get: function() {
        const i = this.positionOptions.findIndex(v => v.key == this.temp.position)
        if (i > -1) {
          return this.positionOptions[i].rate
        }
        return '1:1'
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getPositionString(position) {
      const i = this.positionOptions.findIndex(v => v.key == position)
      if (i > -1) {
        return this.positionOptions[i].label
      }
      return ''
    },
    getList() {
      this.listLoading = true
      fetchCarouselList(this.listQuery).then(response => {
        this.list = response.data
        this.listLoading = false
      }, () => {
        this.listLoading = false
      })
    },
    getImage(url) {
      return this.$utils.getImage(url)
    },
    getStatusString(status) {
      return this.statusOptions[status]
    },
    getStatusType(status) {
      return this.statusType[status]
    },
    // 清空表单
    resetTemp() {
      this.changeImage = false
      this.temp = {
        id: 0,
        title: '',
        url: '',
        bar_color: '',
        open_type: '',
        description: '',
        status: 1,
        pic: '',
        show_level: 0,
        position: 0,
        sort_id: 0
      }
    },
    getOpenTypeString(type) {
      let label = ''
      for (let i = 0; i < this.$store.state.settings.openTypeOptions.length; i++) {
        if (this.$store.state.settings.openTypeOptions[i].key === type) {
          label = this.$store.state.settings.openTypeOptions[i].label
          break
        }
      }
      return label
    },
    // 创建
    handleCreate() {
      if (this.dialogStatus === 'update') {
        this.resetTemp()
      }
      this.temp.id = 0
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 编辑
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 排序更新
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      } else if (prop === 'sort_id') {
        this.sortBySort(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort_id = '+id'
      } else {
        this.listQuery.sort_id = '-id'
      }
      this.getList()
    },
    sortBySort(order) {
      if (order === 'ascending') {
        this.listQuery.sort_id = '+sort'
      } else {
        this.listQuery.sort_id = '-sort'
      }
      this.getList()
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort_id
      if (sort === `+${key}`) {
        return 'ascending'
      } else if (sort === `-${key}`) {
        return 'descending'
      }
    },
    // 上传图片
    uploadImageHandler(callback) {
      if (this.changeImage === true && this.temp.pic) {
        const form = new FormData()
        form.append('imageFile', this.$utils.convertBase64ToFile(this.temp.pic))
        fetchImageUploadNoWater(form).then((res) => {
          this.temp.pic = res.data.url
          this.changeImage = false
          callback()
        }, (err) => {
          this.$notify({
            title: '提示',
            message: err.message || '图片上传失败',
            type: 'error',
            duration: 2000
          })
          this.submitLoading = false
        })
      } else {
        callback()
      }
    },
    // 裁剪图片
    cutDown(obj) {
      this.temp.pic = obj.dataURL
      this.changeImage = true
    },
    // 提交表单
    createData() {
      // 先上传图片
      this.submitLoading = true
      this.uploadImageHandler(this.submitData)
    },
    updateData() {
      // 先上传图片
      this.submitLoading = true
      this.uploadImageHandler(this.submintUpdateData)
    },
    submintUpdateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          fetchUpdateCarousel(this.temp).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.submitLoading = false
          }, () => {
            this.submitLoading = false
          })
        } else {
          this.submitLoading = false
        }
      })
    },
    submitData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          fetchCreateCarousel(this.temp).then((res) => {
            this.temp.id = res.data.id
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.resetTemp()
            this.$notify({
              title: 'Success',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })

            this.submitLoading = false
          }, (err) => {
            console.log(err)
            this.submitLoading = false
          })
        } else {
          this.submitLoading = false
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该轮播图, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '执行中...'

            fetchDeleteCarousel(row.id).then((res) => {
              this.$notify({
                title: 'Success',
                message: '删除成功',
                type: 'success',
                duration: 3000
              })
              this.list.splice(index, 1)

              instance.confirmButtonLoading = false
              done()
            }, (err) => {
              this.$notify({
                title: 'Success',
                message: err.message || '删除失败',
                type: 'error',
                duration: 3000
              })
              instance.confirmButtonLoading = false
              done()
            })
          } else {
            done()
          }
        }
      })
    }
  }
}
</script>

<style>
  .el-dialog {
    width: 550px;
  }

  .icon-uploader {
    border: 1px solid #eee;
    width: 2.5rem;
    height: 2.5rem;
    align-items: center;
    display: flex;
    justify-content: center;
    overflow: hidden;
    cursor: pointer;
  }
  .cate-icon {
    width: 2.5rem;
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
